package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SearchReceiver {
    @Autowired
    private SearchService searchService;

    /**
     * 消费者: 用户搜索服务
     * @param albumId 上传专辑ID
     * @Exchange EXCHANGE_ALBUM
     * @Queue QUEUE_ALBUM_UPPER
     * @RoutingKey ROUTING_ALBUM_UPPER
     * */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true"),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void upperAlbum(Long albumId, Channel channel , Message message){
        searchService.upperAlbum(albumId);
        /**
         * 通过 channel 确认 RabbitMQ 消费者已处理完某条消息，
         * 告知 RabbitMQ 服务器可以安全地从队列中删除这条消息。
         * 由于第二个参数是 false，因此只确认当前消息，而不是批量确认。
         * */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 消费者: 用户搜索服务
     * @param albumId 上传专辑ID
     * @Exchange EXCHANGE_ALBUM
     * @Queue QUEUE_ALBUM_LOWER
     * @RoutingKey ROUTING_ALBUM_LOWER
     * */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true"),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void lowerAlbum(Long albumId, Channel channel , Message message){
        searchService.lowerAlbum(albumId);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
